package com.yy.micro.magic.core.result.value;

import com.yy.micro.magic.core.config.Content;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

public interface ValueStrategy {

    int TRUE_VALUE_STRATEGY = 1<<12|1;
    int EXCLUDE_NULL_VALUE_STRATEGY = TRUE_VALUE_STRATEGY|1<<2;
    int EXCLUDE_EMPTY_VALUE_STRATEGY = TRUE_VALUE_STRATEGY|1<<3;

    int CLEAN_TEMP_VALUE_STRATEGY = TRUE_VALUE_STRATEGY| 1<<10;

    boolean support(int strategy);
    boolean include(ValuePair value);

    @Component
    @Order(88)
    class TrueValueStrategy implements  ValueStrategy{
        @Override
        public boolean include(final ValuePair value) {
            return true;
        }

        @Override
        public boolean support(final int strategy) {
            return (strategy&TRUE_VALUE_STRATEGY) ==TRUE_VALUE_STRATEGY;
        }
    }


    @Component
    @Order(44)
    class NullValueStrategy implements ValueStrategy{

        @Override
        public boolean support(final int strategy) {
            return (strategy& EXCLUDE_NULL_VALUE_STRATEGY) == EXCLUDE_NULL_VALUE_STRATEGY;
        }

        @Override
        public boolean include(final ValuePair value) {
            return null != value.getValue();
        }
    }

    @Component
    @Order(55)
    class EmptyValueStrategy implements ValueStrategy{

        @Override
        public boolean support(final int strategy) {
            return (strategy & EXCLUDE_EMPTY_VALUE_STRATEGY) == EXCLUDE_EMPTY_VALUE_STRATEGY;
        }

        @Override
        public boolean include(final ValuePair value) {
            Object v = value.getValue();
            if (null != v){
                if (Collection.class.isAssignableFrom(v.getClass())){
                    return !((Collection<?>) v).isEmpty();
                }else if(v instanceof Map){
                    return !((Map<?, ?>) v).isEmpty();
                }else if (v instanceof  String){
                    return ((String) v).trim().length()>0;
                }else {
                    return true;
                }
            }
            return false;
        }
    }

    @Component
    @Order(99)
    class CleanTempValueStrategy implements ValueStrategy{

        @Override
        public boolean support(final int strategy) {
            return (strategy & CLEAN_TEMP_VALUE_STRATEGY) == CLEAN_TEMP_VALUE_STRATEGY;
        }

        @Override
        public boolean include(final ValuePair value) {
            String name = value.getName();
            if (name.startsWith(Content.CACHE_TEMP_RESULT_VALUE)){
                name=name.substring(Content.CACHE_TEMP_RESULT_VALUE.length());
                value.updateParent(name,value.getValue());
                return false;
            }
            return true;
        }
    }
}
